package com.gooseeker.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContextEvent;

import org.springframework.context.ApplicationContext;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.gooseeker.dao.MenuDao;
import com.gooseeker.dao.beans.Menu;
import com.gooseeker.modbus.ModbusUtils;
import com.gooseeker.modbus.Parameter;
import com.gooseeker.modbus.SerialPortRecvImpl;

public class SystemInitLoader extends ContextLoaderListener
{
	public void contextInitialized(ServletContextEvent event)
	{
		String webroot = event.getServletContext().getRealPath("/");
		System.setProperty("web.root", webroot);
		// 加载所有资源与权限的关系
		// List<ConfigAttribute> userAttrs = new ArrayList<ConfigAttribute>();
		// userAttrs.add(new SecurityConfig("ROLE_USER"));
		// userAttrs.add(new SecurityConfig("ROLE_ENGINEER"));
		// userAttrs.add(new SecurityConfig("ROLE_ADMIN"));
		// Constants.RESOURCE_MAP.put("/user/**", userAttrs);

		// List<ConfigAttribute> engineerAttrs = new
		// ArrayList<ConfigAttribute>();
		// engineerAttrs.add(new SecurityConfig("ROLE_ENGINEER"));
		// adminAttrs.add(new SecurityConfig("ROLE_ADMIN"));
		// Constants.RESOURCE_MAP.put("/engineer/**", engineerAttrs);

		// List<ConfigAttribute> adminAttrs = new ArrayList<ConfigAttribute>();
		// adminAttrs.add(new SecurityConfig("ROLE_ADMIN"));
		// Constants.RESOURCE_MAP.put("/admin/**", adminAttrs);

		ApplicationContext applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(event.getServletContext());

		MenuDao menuDao = (MenuDao) applicationContext.getBean("menuDaoBean");
		List<Menu> menus = menuDao.getAllAuthorities();

		for (Menu m : menus)
		{
			List<ConfigAttribute> attrs = Constants.RESOURCE_MAP
					.get(m.getUrl());
			if (null == attrs)
			{
				attrs = new ArrayList<ConfigAttribute>();
			}

			attrs.add(new SecurityConfig(m.getRole()));

			Constants.RESOURCE_MAP.put(m.getUrl(), attrs);
		}

		Parameter parameter = (Parameter) applicationContext
				.getBean("parameterBean");
		/**
		 * 默认串口，可配置 TODO 添加配置文件，用于动态加载
		 */
		Constants.DEFAULT_COM_PORT = parameter.getPort();
		/**
		 * 打开串口的等待超时时间
		 */
		Constants.DEFAULT_OPEN_TIMEOUT = parameter.getTimeout();
		/**
		 * 默认波特率
		 */
		Constants.DEFAULT_COM_BUAD_RATE = parameter.getBaudRate();
		/**
		 * 默认数据位
		 */
		Constants.DEFAULT_COM_DATA_BIT = parameter.getDataBits();
		/**
		 * 默认停止位
		 */
		Constants.DEFAULT_COM_STOP_BIT = parameter.getStopBits();
		/**
		 * 默认校验位
		 */
		Constants.DEFAULT_COM_PARITY = parameter.getParity();

		Constants.ADC_PRECISION = parameter.getAdcPrecision();

		Constants.ADC_VOLTAGE_RANGE = parameter.getVoltageRange();

		Constants.FAIL_THRESHOLD = parameter.getFailthreshold();

		Constants.PASS_THRESHOLD = parameter.getPassThreshold();

		Constants.PASS_ADC_THRESHOLD_VALUE = (int) (Math.pow(2,
				parameter.getAdcPrecision())
				/ parameter.getVoltageRange() * parameter.getPassThreshold());

		Constants.FAIL_ADC_THRESHOLD_VALUE = (int) (Math.pow(2,
				parameter.getAdcPrecision())
				/ parameter.getVoltageRange() * parameter.getFailthreshold());

		System.out.println("SystemInitLoader pass threshod value: " + Constants.PASS_ADC_THRESHOLD_VALUE);
		System.out.println("SystemInitLoader fail threshod value: " + Constants.FAIL_ADC_THRESHOLD_VALUE);
		System.out
				.println("SystemInitLoader COM:" + Constants.DEFAULT_COM_PORT);
		// ModbusUtils.getInstance().open(Constants.DEFAULT_COM_PORT);

		Constants.PAGE_NUM = parameter.getPageNum();

		Constants.CMD_RESEND_TIMES = parameter.getResendTime();

		Constants.CMD_RESEND_PERIOD = parameter.getResendPeriod();
		System.out.println("SystemInitLoader: resend times = "
				+ Constants.CMD_RESEND_TIMES);
		System.out.println("SystemInitLoader: resend period = "
				+ Constants.CMD_RESEND_PERIOD);

		Constants.PASS_RESULT_DELTA = parameter.getPassResultDelta();
		Constants.FAIL_RESULT_DELTA = parameter.getFailResultDelta();
		Constants.UNUSE_RESULT_DELTA = parameter.getUnuseResultDelta();
		System.out.println("SystemInitLoader: pass delta = "
				+ Constants.PASS_RESULT_DELTA);
		System.out.println("SystemInitLoader: fail delta = "
				+ Constants.FAIL_RESULT_DELTA);
		System.out.println("SystemInitLoader: unuse delta = "
				+ Constants.UNUSE_RESULT_DELTA);
	}

	public void contextDestroyed(ServletContextEvent event)
	{
		Constants.RESOURCE_MAP.clear();
		//关闭串口
		ModbusUtils.getInstance().close();
		//释放解析线程资源
		SerialPortRecvImpl.runFlag = false;
	}

}
